import axios from 'axios';
import service from './api';
import { Loading,Message,MessageBox } from 'element-ui';
import  router   from '@/router/index';
import store from '@/store'


// 创建axios实例
let instance = axios.create({
  // 设置代理了 不需要填写baseUrl地址 代理设置 config下的index.js文件 proxyTable属性
 // baseURL: 'http://192.25.102.19:8899',
  // 超时设置30秒
  timeout: 1000*30
});


//包裹请求方法的容器
const Http = {};
//console.info(service);
//service 循环遍历输出不同的请求方法
for (let key in service) {
  //console.info("key:"+key);
  for(let methodName in service[key]){
   // console.info("a:"+methodName);
   // console.info("a api:"+service[key][methodName]);
   // console.info("a api url:"+service[key][methodName].url);
   // console.info("a api method:"+service[key][methodName].method);
    let api = service[key][methodName];
    Http[methodName] =  function (params, isFormData = false, config = {}) {
      let newParams = {};
      //contact-type是否是form-data的判断
      if (params && isFormData) {
        newParams = new FormData();
        for (let i in params) {
          newParams.append(i, params[i]);
        }
      } else {
        newParams = params;
      }

      //不同请求的判断
      let response = {}; //请求的返回值
      if (api.method === 'put' || api.method === 'post' || api.method === 'patch') {
        try {

          response =  instance[api.method](api.url, newParams, config);
        } catch (err) {
          response = err;
        }
      } else if (api.method === 'get' || api.method === 'delete') {
        config.params = newParams;
        try {
          response =  instance[api.method](api.url, config);
        } catch (err) {
          response = err;
        }
      }
      return response;
    }
  }

}

let loading = null;
//拦截器
instance.interceptors.request.use(config => {
  //发起请求前做什么
  // 设置header Authorization   登录不需要设置header token认证
  if(!config.url.endsWith("/login")){
   // config.headers["Authorization"]=JSON.parse(localStorage.getItem("userInfo")).token;
    config.headers["Authorization"]=store.getters.token;
  }
  //登录和登出不需要loding
  if(!config.url.endsWith("/login")||!config.url.endsWith("/logout")){
    /*loading = Loading.service({
      text :"拼命加载中......"
    });*/
  }

  return config;
}, err => {
 //console.log('err',err.response);
  //请求错误
 /* if(loading!=null){
    loading.close();
  }*/

  Message.error({
    message : "请求超时，请稍后重试",
    duration : 3000
  });
  // 对请求错误做些什么
  return Promise.reject(err)
});
instance.interceptors.response.use(res => {
 /* if(loading!=null){
    loading.close();
  }*/

  if(res.data.code !== 0) { // 本后台只有code为0时是成功；根据自己的情况自己写逻辑
     if(res.data.message=='token has expired and is no longer valid!'){
       // token失效 需要跳转到登录界面
       MessageBox.alert('token过期请重新登录', '提示', {
         confirmButtonText: '确定',
         showClose:'false',
         type:'warning',
         callback: action => {
           // 清空当前用户对象
           store.commit('CLEAN_USER_INFO')
           //localStorage.removeItem("userInfo")
           router.push({ path: '/login' });
         }
       });
     }else{
       Message.error({
         message : res.data.message,
         duration : 3000
       });
     }
    return Promise.reject(res.data.message)
  } else {
    // 处理token快过期自动刷新服务器返回的新token
    console.log("res",res);
    console.log("typeof",typeof(res.headers.refresh_token));

    if(typeof(res.headers.refresh_token) != "undefined" ){
      if(res.headers.refresh_token){
        //let userInfo = JSON.parse(localStorage.getItem("userInfo"));
       // userInfo.token=res.headers.refresh_token;
       // localStorage.setItem("userInfo",JSON.stringify(userInfo));
        // 刷新token
        store.commit('SET_USER_TOKEN',res.headers.refresh_token)
        console.log("refreshToken")
      }
    }
    return res.data;
  }
}, err => {
 console.log('err',err.response);
  /*if(loading!=null){
    loading.close();
  }*/

 /* Message.error({
    message : "请求错误，请稍后重试",
    duration : 3000
  });*/
  return Promise.reject(err)
});

export default Http;
